import axios from 'axios'
import md5 from 'js-md5'
import { Toast } from 'vant'
import store from '@/store'
import { getBaseUrl } from './envUrl'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    config.baseURL = getBaseUrl(config.options && config.options.domain)

    if (config.options && config.options.login && store.state.user && store.state.user.token) {
      config.data = Object.assign(
        {},
        {
          userIdentification: store.state.user.id,
          userToken: store.state.user.token
        },
        config.data
      )
    }

    config.headers = Object.assign(config.headers, signPlusByMd5(config.data))

    // config.transformRequest = [
    //   function(data) {
    //     let ret = ''
    //     for (let it in data) {
    //       ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
    //     }
    //     return ret
    //   }
    // ]

    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 1) {
      Toast({
        message: res.message || 'Error'
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Toast({
      message: error.message || 'Error'
    })
    return Promise.reject(error)
  }
)

/**
 * 新签名规则
 * @deprecated 约定各个体系签名统一
 * @param {Object} dataBody
 */
const signPlusByMd5 = (dataBody = {}, options = {}) => {
  const {
    signKey = 'XTSIGNKEY', // 秘钥
    header = {}, // 自定义header
    signType = 'MD5' // 签名方式 默认md5
  } = options
  let xtapiValidateCdk = '' // 复杂对象属性
  let xtapiValidateCdkArr = '' // 复杂对象属性(数组)

  if (!dataBody) {
    return
  }

  var timeStamp = new Date().getTime()
  var dataTotal = {
    // 'xtapi-validate-channelNo': channelNo,
    // 'xtapi-validate-bizLine': bizLine,
    'xtapi-validate-timestamp': timeStamp,
    'xtapi-validate-nonce': Math.random()
      .toString(36)
      .substr(-10),
    ...header
  } // 签名数据

  for (var i in dataBody) {
    if ([null, undefined, ''].includes(dataBody[i])) {
      delete dataBody[i]
    }

    if (dataBody[i] instanceof Array) {
      dataBody[i] = JSON.stringify(dataBody[i])
      xtapiValidateCdkArr += `${i}|`
    } else if (typeof dataBody[i] === 'object') {
      dataBody[i] = JSON.stringify(dataBody[i])
      xtapiValidateCdk += `${i}|`
    }
  }

  // 复杂对象header添加字段
  if (xtapiValidateCdk.length) {
    xtapiValidateCdk = xtapiValidateCdk.substr(0, xtapiValidateCdk.length - 1)
    // dataTotal['xtapi-validate-cdk'] = xtapiValidateCdk
    dataTotal['xtapi-validate-complex-params'] = xtapiValidateCdk
  }
  if (xtapiValidateCdkArr.length) {
    xtapiValidateCdkArr = xtapiValidateCdkArr.substr(0, xtapiValidateCdkArr.length - 1)
    dataTotal['xtapi-validate-complex-array-params'] = xtapiValidateCdkArr
  }

  const signStr = Object.keys(dataBody).length === 0 ? getSign(dataTotal) : `${getSign(dataBody)}&${getSign(dataTotal)}`
  const sign = paramsStrSort(signStr) // 获取签名sign
  // var sign = paramsStrSort(`${getSign(dataBody)}&${getSign(dataTotal)}`) // 获取签名sign

  // delete dataTotal['xtapi-validate-body']
  dataTotal['xtapi-validate-signature'] = sign
  dataTotal['xtapi-validate-signtype'] = signType

  return dataTotal

  function getSign (params) {
    var arr = []
    for (var i in params) {
      arr.push(i + '=' + params[i])
    }
    return arr.sort().join('&')
  }

  function paramsStrSort (paramsStr) {
    var newUrl = paramsStr + signKey
    // console.log('newUrl：' + newUrl)
    return md5(newUrl)
  }
}

export default service
